package xyz.vmcserver.wdibbs.model.service.impl;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Service;
import xyz.vmcserver.wdibbs.model.dao.ArticleMapper;
import xyz.vmcserver.wdibbs.model.dao.UserGroupMapper;
import xyz.vmcserver.wdibbs.model.dao.UserMapper;
import xyz.vmcserver.wdibbs.model.dao.UserRegisterInfoMapper;
import xyz.vmcserver.wdibbs.model.po.ArticleView;
import xyz.vmcserver.wdibbs.model.po.UserView;
import xyz.vmcserver.wdibbs.model.service.ToolsService;
import xyz.vmcserver.wdibbs.model.service.UserService;
import xyz.vmcserver.wdibbs.model.vo.User;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

@Service("userService")
public class UserServiceImpl implements UserService {
    public SqlSession sqlSessionInit(){
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = build.openSession();
        return sqlSession;
    }
    public String br="-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n";
    ToolsService toolsService = new ToolsService();
    @Override
    public Boolean register(User user) {
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            if(Objects.equals(user.getAlias(), "")|| Objects.equals(user.getAlias(), " ")){
                user.setAlias(null);
            }
            String salt = toolsService.getRandomStr(20);
            user.setSalt(salt);
            user.setPassword(toolsService.getSHA256Str(user.getPassword()+salt));
            user.setGroup_alias("USER_UNACTIVATED");
            user.setScore(0);
            userMapper.insertUser(user);
            UserRegisterInfoMapper uriMapper = sqlSession.getMapper(UserRegisterInfoMapper.class);
            System.out.println("timeMillis:"+System.currentTimeMillis());;
            uriMapper.insertURI(user.getUsername(),System.currentTimeMillis(),"127.0.0.1",toolsService.getRandomStr(8));
            sqlSession.commit();
            sqlSession.close();
            return true;
        } catch (IOException e) {
            System.out.println("注册失败,出现异常");
            return false;

//            throw new RuntimeException(e);
        }

    }

    @Override
    public User login(User user) {
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //通过用户名获取盐值
            String salt = mapper.selectSaltByUsername(user.getUsername());
            if(null==salt){
                System.out.println(br+"|x|获取用户:"+user.getUsername()+"的盐值失败，该用户不存在！");
                return null;
            }
            System.out.println(br+"|!|用户盐值:"+salt);
            //将用户前台输入的密码加盐并SHA256
            String oAuth = toolsService.getSHA256Str(user.getPassword()+salt);
            System.out.println(br+"|!|用户:"+user.getUsername()+"尝试登录，口令:"+oAuth);
            //设置前台输入用户实体的密码为加盐后SHA256的密码口令
            user.setPassword(oAuth);
            //查找用户
            User respUser = mapper.selectByUsernameAndPassword(user);
            if(null!=respUser){
                System.out.println(br+"|v|登录成功！alias:"+respUser.getAlias());
                return respUser;
            }else{
                System.out.println(br+"|x|登录失败！");
                return null;
            }
        } catch (IOException e) {
            System.out.println(br+"|x|登录失败,出现异常！");
            return null;
//            throw new RuntimeException(e);
        }
    }

    @Override
    public Boolean active(String code) {
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            UserRegisterInfoMapper uriMapper = sqlSession.getMapper(UserRegisterInfoMapper.class);
            System.out.println("获取成功"+getClass().getName());
            uriMapper.updateActivationTimeByCode(code);
            userMapper.updateUserGroupByActivationCode(code,"USER_LEVEL1");
            sqlSession.commit();
            sqlSession.close();
            return true;
        } catch (IOException e) {
//            throw new RuntimeException(e);
            System.out.println("获取出错"+getClass().getName());
            return false;
        }

    }

    @Override
    public UserView userInfo(String username) {
        SqlSession sqlSession = sqlSessionInit();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        UserView reUser = mapper.selectUserByUsername(username);
        return reUser;
    }

    @Override
    public String[] getGroupInfo(String groupAlias) {
        InputStream resourceAsStream = null;
        String[] groupInfo = new String[2];
        try {
            resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            UserGroupMapper userGroupMapper = sqlSession.getMapper(UserGroupMapper.class);
            groupInfo[0] = String.valueOf(userGroupMapper.selectPermissionByGroupAlias(groupAlias));
            groupInfo[1] = userGroupMapper.selectGroupNameByGroupAlias(groupAlias);
            return groupInfo;
        } catch (IOException e) {
            System.out.println("组信息获取失败,出现异常!");
            return null;
//            throw new RuntimeException(e);
        }
    }

    @Override
    public List<UserView> searchUserByKeyAndValuePages(String value, Integer page, String sortType, String sortValue) {
        if(null==value){
            return null;
        }
        if(null==sortType){
            sortType = "ASC";
        }
        if(null==sortValue){
            sortValue = "score";
        }
        SqlSession sqlSession = sqlSessionInit();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<UserView> userViews = mapper.searchUserByKeyAndValuePages(value, (page-1)*20, sortType, sortValue);
        return userViews;
    }

}
